<?php

namespace app\common\library;
use think\facade\Config;
class YuPust
{
    const VERSION = '6.0.5';

    protected $errorString = '';

    public static $instance ;

    /**
     * @title 单例调用
     * @description 单例调用
     * @author Admin ldy
     * @time 2018/9/25  12:22
     */
    public static function getInstance(){
        if (YuPust::$instance == null){
            YuPust::$instance = new \app\common\library\YuPust;
            return YuPust::$instance;
        }else{
            return YuPust::$instance;
        }
    }

    public function __construct(){
        //初始化
    }

    public function setErrorString($msg){
        $this->errorString = $msg;
    }

    public function getErrorString(){
        return $this->errorString;
    }

    public static function getPushUrl(){
        return Config::get('scj.push_url');
    }

    public static function getPushKey(){
        return Config::get('scj.push_key');
    }

    public static function getPushPa(){
        return Config::get('scj.push_pa');
    }


    public static function pushMsgBase($func,$options,$type = 'queue'){
        $url = YuPust::getPushUrl();
        $key = YuPust::getPushKey();
        $pa = YuPust::getPushPa();
        $postString = ['key'=>$key,'pa'=>$pa,'func'=>$func,'options'=>json_encode($options)];

        if ($type=='queue'){
            $jobHandlerClassName = 'app\common\job\PushMsgToUid';
            $jobData = ['postString'=>$postString,'url'=>$url];
            $re = \app\common\library\YuActivity::addMessageQBase($jobHandlerClassName,$jobData,1);
        }else{
            $re = \app\common\library\YuPost::post($url,$postString);
        }
        if ($re){
            return new ReSuccess('推送成功！',$re);
        }else{
            return new ReFail('推送失败！',$re);
        }
    }

    public static function pushMsgToClient($client_id,$message){
        $type = 'webPush';
        $jsonmsg = json_encode(['type'=>$type,'message'=>$message]);
        $func = 'sendToClient';
        $options=['client_id'=>$client_id,'data'=>$jsonmsg];
        return YuPust::pushMsgBase($func,$options);
    }

    public static function pushMsgToUid($uid,$message,$type='webPush'){
        $jsonmsg = json_encode(['type'=>$type,'message'=>$message]);
        $func = 'sendToUid';
        $options=['uid'=>$uid,'data'=>$jsonmsg];
        return YuPust::pushMsgBase($func,$options);
    }

    public static function getClientIdByUid($uid){
        $func = 'getClientIdByUid';
        $options=['uid'=>$uid,'data'=>''];
        return YuPust::pushMsgBase($func,$options);
    }

    public static function getPushClientCount(){
        $func = 'getAllClientCount';
        $options="";
        return YuPust::pushMsgBase($func,$options,'post');
    }



}
